package main

import (
	"fmt"
	"time"
)

func main() {
	// chanDemo3()
	// bufferedChannel()
	channelClose()
}

func chanDemo() {
	// channel  里面内容 int , 此时chan -> nil
	// var c chan int
	c := make(chan int)

	go func() {
		// 收数据
		for {
			n := <-c
			fmt.Println(n)
		}

	}()
	// 向 chan 发数据
	c <- 1
	c <- 2
}

// channel 作为返回值
func worker3(id int) chan int {
	c := make(chan int)
	go func() {
		for {
			fmt.Printf("Worker %d received %c\n",
				id, <-c)
		}
	}()
	return c
}

func worker2(id int, c chan int) {
	for {
		fmt.Printf("Worker %d received %c\n",
			id, <-c)
	}
}

func worker(id int, c chan int) {
	// 有值则继续收,对应close chan
	for n := range c {
		fmt.Printf("Worker %d received %c\n",
			id, n)
	}
}

// 将十个channel 分发给十个worker
// channel 作为返回值  | <-chan int(只能发数据)
func createWorker(id int) chan<- int {
	c := make(chan int) // 创建 chan
	go worker(id, c)    // 开 goroutine
	return c            // 立即返回
}

func chanDemo3() {
	// 创建十个 channel
	var channels [10]chan<- int // 每一个worker建一个channel
	for i := 0; i < 10; i++ {   // 开十个worker
		channels[i] = createWorker(i)
	}

	// 给是个人发送数据
	for i := 0; i < 10; i++ {
		channels[i] <- 'a' + i
	}

	for i := 0; i < 10; i++ {
		channels[i] <- 'A' + i
	}

	time.Sleep(time.Millisecond)
}

// 缓冲区是3
func bufferedChannel() {
	c := make(chan int, 3)
	go worker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd' // 第四个才deadlock
	time.Sleep(time.Millisecond)
}

// 关闭chan，不一定要close
func channelClose() {
	c := make(chan int)
	go worker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd'
	close(c)
	time.Sleep(time.Millisecond)
}
